import { api } from './api'
import type { ApiResponse, PaginatedResponse, PaginationParams } from '../types'

interface SystemLog {
  id: number
  type: 'INFO' | 'WARNING' | 'ERROR' | 'DEBUG'
  level: 'LOW' | 'MEDIUM' | 'HIGH'
  module: 'AUTH' | 'USER' | 'ARTICLE' | 'COMMENT' | 'SYSTEM'
  action: string
  description: string
  params?: Record<string, any>
  ipAddress?: string
  user?: {
    id: number
    username: string
  }
  createdAt: string
}

interface GetLogsParams extends PaginationParams {
  type?: SystemLog['type']
  level?: SystemLog['level']
  module?: SystemLog['module']
  startDate?: string
  endDate?: string
  userId?: number
}

interface LogStats {
  totalLogs: number
  logsByType: {
    type: SystemLog['type']
    count: number
  }[]
  logsByLevel: {
    level: SystemLog['level']
    count: number
  }[]
  logsByModule: {
    module: SystemLog['module']
    count: number
  }[]
  recentErrors: SystemLog[]
  activityTrend: {
    date: string
    count: number
  }[]
}

export const logsApi = api.injectEndpoints({
  endpoints: (builder) => ({
    getLogs: builder.query<ApiResponse<PaginatedResponse<SystemLog>>, GetLogsParams>({
      query: (params) => ({
        url: '/logs',
        params,
      }),
      providesTags: (result) =>
        result
          ? [
              ...result.data.content.map(({ id }) => ({ type: 'Log' as const, id })),
              { type: 'Log' as const, id: 'LIST' },
            ]
          : [{ type: 'Log' as const, id: 'LIST' }],
    }),

    getLog: builder.query<ApiResponse<SystemLog>, number>({
      query: (id) => `/logs/${id}`,
      providesTags: (result) =>
        result ? [{ type: 'Log' as const, id: result.data.id }] : [],
    }),

    getLogStats: builder.query<ApiResponse<LogStats>, { startDate: string; endDate: string }>({
      query: (params) => ({
        url: '/logs/stats',
        params,
      }),
      providesTags: ['Log'],
    }),

    clearLogs: builder.mutation<ApiResponse<void>, { before: string; type?: SystemLog['type'] }>({
      query: (params) => ({
        url: '/logs',
        method: 'DELETE',
        params,
      }),
      invalidatesTags: [{ type: 'Log', id: 'LIST' }],
    }),

    exportLogs: builder.query<Blob, GetLogsParams>({
      query: (params) => ({
        url: '/logs/export',
        params,
        responseHandler: (response) => response.blob(),
      }),
    }),

    getErrorLogs: builder.query<ApiResponse<SystemLog[]>, { limit?: number }>({
      query: (params) => ({
        url: '/logs/errors',
        params,
      }),
      providesTags: ['Log'],
    }),

    getAuditLogs: builder.query<ApiResponse<SystemLog[]>, { userId: number; limit?: number }>({
      query: (params) => ({
        url: '/logs/audit',
        params,
      }),
      providesTags: ['Log'],
    }),
  }),
})

export const {
  useGetLogsQuery,
  useGetLogQuery,
  useGetLogStatsQuery,
  useClearLogsMutation,
  useExportLogsQuery,
  useGetErrorLogsQuery,
  useGetAuditLogsQuery,
} = logsApi 